﻿using AutoMapper;
using B.S.BasicData.Api.Read.Extensions;
using B.S.BasicData.Api.Write.Application.Command.Account;
 
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MD5Hash;
using MediatR;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Write.Application.Handler.Account
{
    /// <summary>
    /// 中介者新增账号处理类
    /// </summary>
    public class CreateAccountHandler : IRequestHandler<CreateAccountCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IBaseRepository<AccountRoleModel> accountRoleRepo;
        private readonly ILogger<CreateAccountHandler> logger;
        private readonly IMapper mapper;
        private readonly IBaseRepository<LogModel> logRepo;

        public CreateAccountHandler(IBaseRepository<AccountModel> accountRepo, IBaseRepository<RoleModel> roleRepo, IBaseRepository<AccountRoleModel> accountRoleRepo, ILogger<CreateAccountHandler> logger,IMapper mapper,IBaseRepository<LogModel> logRepo)
        {
            this.accountRepo = accountRepo;
            this.roleRepo = roleRepo;
            this.accountRoleRepo = accountRoleRepo;
            this.logger = logger;
            this.mapper = mapper;
            this.logRepo = logRepo;
        }

        /// <summary>
        ///  中介者新增账号处理处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(CreateAccountCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            logger.LogInformation("您正在添加账号,账号:"+request.AccountName);

            //1.构建要添加的账号实体对象
            var accountModel = mapper.Map<AccountModel>(request);  //把前端传过来的参数转成账号实体
            //密码怎么办?
            string last6 = accountModel.CardId.Substring(accountModel.CardId.Length - 6);  //取后6位
             
            accountModel.Salt =this.GenerateSalt();//生成盐
            accountModel.Pwd = last6.GetMD5WithSalt(accountModel.Salt);//密码加盐加密
            accountModel.Id = YitIdHelper.NextId(); //指定Id

           

            //角色关系的数据

            //3.构建账号角色关系的实体对象
            var accountRole = new AccountRoleModel() { 
                Id = YitIdHelper.NextId(),
                AccountId = accountModel.Id,
                RoleId = request.RoleId
            };

            var r1 = 0;
            var r2 = 0;
            //分布式事务
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    //2.把对象保存到数据库,要用到仓储
                    r1 = await accountRepo.CreateAsync(accountModel);
                    //4.把对象保存到数据库,要用到仓储
                    r2 = await accountRoleRepo.CreateAsync(accountRole);
                    tran.Complete();  //事务成功
                }
                catch (Exception)
                {
                    //会自动回滚
                    logger.LogError("添加新账户时发生异常,事务回滚.");
                }
            }



            //5.构建业务日志实体对象

            var logModel = new LogModel
            {
                Id = YitIdHelper.NextId(),
                CreateTime = DateTime.Now,
                Creator = request.Creator,
                LogDes = $"创建{request.RealName}账号成功" 
            };
            //6.把对象保存到数据库,要用到仓储
            logRepo.CreateAsync(logModel);


            if (r1 > 0 && r2 > 0) {
                res.Msg = "创建管理员账号成功!";
                res.Data = r1;
                res.Code = ApiEnum.Success;
            }
            else { 
              res.Msg = "创建管理员账号失败!";
                res.Data = 0;
                res.Code = ApiEnum.Failed;
            }

            return res;
             
        }
    }
}
